/**
 * HTTP 请求工具类
 */
function appendHost(url) {
    return "/shop-api/" + url;
}

/**
 * get无参数
 * @param url
 * @param callback 函数
 */
function httpGetNoParams(url, callback) {
    //url 拼接服务器ip和端口地址
    url = appendHost(url);

    $.get(url, function (resp) {
        handleResp(resp, callback);
    });
}


/**
 * get有参数
 * @param url
 * @param params
 * @param callback
 */
function httpGet(url, params, callback) {
    //url 拼接服务器ip和端口地址
    url = appendHost(url);
    $.get(url, params, function (resp) {
        handleResp(resp, callback);
    })
}

/**
 * post有参数
 * @param url
 * @param params
 * @param callback
 */
function httpPost(url, params, callback) {
    //url 拼接服务器ip和端口地址
    url = appendHost(url);
    let paramsJson = JSON.stringify(params);
    $.ajax({
        type: "POST",
        url: url,
        contentType: "application/json; charset=utf-8",
        data: paramsJson,
        success: function (resp) {
            handleResp(resp, callback);
        }
    });
}

function convertToFormData(params) {
    var data = new FormData();
    for (var key in params) {
        data.append(key, params[key]);
    }
    return data;
}

/**
 * 请求上传文件
 * @param url
 * @param params
 * @param respCallBack
 */
function httpPostWithFile(url, params, respCallBack) {
    url = appendHost(url);
    var data = convertToFormData(params);
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        cache: false,
        processData: false,
        contentType: false,
        success: function (resp) {
            handleResp(resp, respCallBack);
        }
    });
}

function isjson(obj){
    var  isjson = typeof (obj) == "object"  && Object.prototype.toString.call(obj).toLowerCase() == "[object object]"  && !obj.length;
    return  isjson;
}

function handleResp(resp, callback) {
    // code:业务处理状态
    // msg:提示信息
    // data:业务数据
    console.log("===resp===");
    console.log(resp);
    var result;
    if(!isjson(resp)){
        result = JSON.parse(resp);
    }
    result = resp;

    if (result.code == 0) {
        //业务处理成功，调用处理结果回调方法
        callback(result.data);
    } else if (result.code == 1000) {
        //未登录
        location.href = "userLogin.html";
    } else {
        //业务处理失败
        alert(result.message);
    }
}